package com.by.redis.support;

import com.by.redis.serializer.FastJson2RedisSerializer;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

public class RedisTemplateSupport {

    /**
     * 构建json序列化的RedisTemplate
     * @param factory
     * @return
     */
    public static RedisTemplate<String, Object> buildJsonRedisTemplate(LettuceConnectionFactory factory){
        RedisTemplate<String, Object> template = new RedisTemplate<>();

        template.setConnectionFactory(factory);

        //自定义fastjson2序列化配置
        FastJson2RedisSerializer<Object> json2RedisSerializer = new FastJson2RedisSerializer<>(Object.class);

        //key使用String的序列化方式
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        //value的key使用jackson的序列化方式
        template.setValueSerializer(json2RedisSerializer);

        //hash的key也是用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        //hash的value也是用jackson的序列化方式
        template.setHashValueSerializer(json2RedisSerializer);
        template.afterPropertiesSet();

        return template;
    }

}
